'''Resubmits a denied Dell Self-Dispatch Support Request.'''
from datetime import datetime
from dateparser import parse as dateparser_parse
import PySimpleGUI as sg
from warranty_manager.gui.confirmation import get_confirmation
from warranty_manager.claim.dell.request_resubmitter_layout import layout
from warranty_manager.claim.dell.handlers import (
    handle_load_parts,
    handle_add_part,
    handle_view_parts,
    handle_replace_parts,
    handle_remove_part,
    handle_add_note,
    handle_view_note,
    validate_resubmitted_request,
    validate_common,
)
from warranty_manager.claim.dell.common import get_access_token
from warranty_manager.claim.dell.dispatch_api import (
    get_dispatch_status,
    resubmit_dispatch,
    bulk_dispatches_inquiry,
)


part_nums_dict = None
request_info = {
    'dispatch code': None,
    'parts': [],
    'note': None,
}

window = sg.Window('Dell Self-Dispatch Request Resubmitter', layout)

while True:
    event, values = window.read()

    if event in (None, 'Cancel'):
        break
    elif event == '-LOAD_PARTS-':
        part_nums_dict = handle_load_parts(window)
    elif event == '-ADD_PART-':
        handle_add_part(window, part_nums_dict, request_info['parts'])
    elif event == '-VIEW_PARTS-':
        handle_view_parts(request_info['parts'])
    elif event == '-REMOVE_PART-':
        handle_remove_part(window, request_info['parts'])
    elif event == '-REPLACE_PARTS-':
        handle_replace_parts(window, part_nums_dict, request_info['parts'])
    elif event == '-ADD_NOTE-':
        request_info['note'] = handle_add_note(window, request_info['note'])
    elif event == '-VIEW_NOTE-':
        handle_view_note(request_info['note'])
    elif event == '-REMOVE_NOTE-':

        if not request_info['note']:
            sg.popup('There is no note to remove!', title='Info')
        elif get_confirmation('remove the note from the request'):
            request_info['note'] = ''
            window['-ADD_NOTE-'].update('Add Note')
        else:
            continue

    elif event == '-REPLACE_NOTE-':

        if not request_info['note']:
            sg.popup('There is no note to replace!', title='Info')
        elif get_confirmation('replace the current note with a new one'):
            request_info['note'] = ''
            request_info['note'] = handle_add_note(window, request_info['note'])
        else:
            continue

    elif event == 'Get Status':
        try:
            username, password, dispatch_code, sandbox = validate_resubmitted_request(values)
        except TypeError:
            continue

        request_info['dispatch code'] = dispatch_code

        if get_confirmation('get the status for the specified dispatch code'):
            token = get_access_token('Dispatch', sandbox=sandbox)

            if token:
                get_dispatch_status(
                    username, password, token, dispatch_code, sandbox=sandbox
                )

    elif event == 'Bulk Inquiry':
        try:
            username, password, sandbox = validate_common(values)
        except TypeError:
            continue

        date_tuple = sg.popup_get_date(
            start_mon=datetime.now().month,
            start_day=datetime.now().day,
            start_year=datetime.now().year,
            begin_at_sunday_plus=0,
            no_titlebar=True,
            title="Choose Date",
            keep_on_top=True,
            location=(None, None),
            close_when_chosen=False,
            icon=None,
            locale=None,
            month_names=None,
            day_abbreviations=None,
            modal=True
        )

        if not date_tuple:
            sg.popup_error('You must enter a valid date!', title='Error')
            continue
        else:
            created_from = dateparser_parse(f"{date_tuple[0]}-{date_tuple[1]}-{date_tuple[2]}")

            if get_confirmation(
                    f"Get all bulk dispatch information from {created_from.strftime('%m/%d/%y')} "
                    "to the present"):
                token = get_access_token('Dispatch', sandbox=sandbox)

                if token:
                    bulk_dispatches_inquiry(
                        username, password, token, created_from, sandbox=sandbox
                    )
            else:
                continue

    elif event == 'Resubmit':
        try:
            username, password, dispatch_code, sandbox \
            = validate_resubmitted_request(values, request_info)
        except TypeError:
            continue

        request_info['dispatch code'] = dispatch_code

        if get_confirmation(f"resubmit dispatch #{dispatch_code}"):
            token = get_access_token('Dispatch', sandbox=sandbox)

            if token:
                resubmit_dispatch(
                    username, password, token, request_info, sandbox=sandbox
                )

    else:
        continue

window.close()
